<?php
namespace App\Controllers;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 *
 * @package CodeIgniter
 */

use App\Services\comm;
use CodeIgniter\Controller;
use Config\Services;
use Firebase\JWT\JWT;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class Base extends Controller {
	/**
	 * An array of helpers to be loaded automatically upon
	 * class instantiation. These helpers will be available
	 * to all other controllers that extend BaseController.
	 *
	 * @var array
	 */
	protected $helpers = ['html','Form'];

    protected $clentId = '168f0bdfd2ef6215';
    protected $secretKey = '168f0bdfd2ef6215';
    /**
     * Session 设置
     */
    protected $session;
	/**
	 * Constructor.
	 */
	public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
	{
		// Do Not Edit This Line
		parent::initController($request, $response, $logger);
        // Ajax 跨域请求
        $this->response->setHeader('Access-Control-Allow-Origin','*');
        $this->response->setHeader('Access-Control-Allow-Methods','GET,POST,PUT,DELETE');
        //
        $this->response->setHeader('Access-Control-Allow-Headers','Origin,token, X-Requested-With, Content-Type, Accept,Authorization');
		//--------------------------------------------------------------------
		// Preload any models, libraries, etc, here.
		//--------------------------------------------------------------------
		// E.g.:
        $this->session = \Config\Services::session();

	}

	private function _set_header(){
        $this->response->removeHeader('Set-Cookie');
    }

    function display( $data = [] , $options = []){
        return display($data, $options );
    }
    function render( $data = [] ){
        $data['layout'] = 'Html';
        return display($data);
    }

    function toJson($data = array(),$head = [],$status = 0,$message = 'Success'){
        $this->_set_header();
        if(count($head)>0) {
            foreach($head as $k=>$v) {
                $this->response->setHeader($k,$v);
            }
        }
        if (is_array($data)) {
            if (!array_key_exists('msg', $data)) {
                $data['msg'] = $message;
            }
            if (!array_key_exists('code', $data)) {
                $data['code'] = $status;
            }
        } else{
            $data = ['code'=>$status,'msg'=>$data];
        }
        $data['status'] = 0;
        // 销毁
        if ( array_key_exists('code', $data) && ( $data['code'] || $status && $this->request->getMethod() == 'post' ) ) {
            form_destroy_guid( $this->U('guid') );
        }
        $outStr=preg_replace('/":null/', '":""', $this->jsonGet($data));
        return $this->response->setJSON($outStr);
    }

    protected function jsonGet($result) {
        return json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

    protected function setError( $msg = '' , $code = false ){
        $this->_set_header();
        if(is_object($msg) || is_array($msg)) {
            $message = [];
            foreach ( $msg as $k=>$m ) {
                $message[] = $m;
            }
            $msg = join('  ',$message);
        }
        $data = ['code'=> $code ,'msg'=>$msg?:'请求失败'];
        $outStr = preg_replace('/":null/', '":""', $this->jsonGet($data));
        return $this->response->setJSON($outStr);
    }

    protected function request($index = null,$filter = null){
	    if($this->request->getMethod()=='post'){
	       return $this->request->getPost($index,$filter);
	    }else if($this->request->getMethod()=='get'){
	       return $this->request->getGet($index,$filter);
	    }else {
            return $this->request->getGetPost($index, $filter);
	    }
    }

    protected function U($index = null,$filter = null){
        $resp_data = $this->request($index,$filter);
	    return $resp_data;
    }

    function actionAuth($chkpromise = false, $action_path = '') {
	    return $this->signature( $action_path , $action_path );
	}

    // 判断验签及权限
    protected function signature( $chkpromise = false , $action_path = '' ){
        $GET_URI = new \CodeIgniter\HTTP\URI(current_url(true));
        $URI = $GET_URI->getPath();

        $code = 0 ;
        $data = $this->ckAuthoriztion();
        // 判断权限
        if( is_bool( $chkpromise ) && $data['code'] ) {
            $routes = Services::router();
            $ctln = $routes->controllerName();
            if( $chkpromise && $data->data->id )  {
                $ctl = explode('\\',$ctln);
                if ( !$action_path )
                    $action_path = sprintf('%s/%s/%s',$ctl[3],$ctl[4],$routes->methodName());
                $actionKey = $action_path;
                if(check_action( $data->data->id ,$actionKey)) return 100001;
            }
        }

        function operation_log($data){
            $db = new \App\Models\Admin\OperationsLog();
            return $db->save($data);
        }


        $aKey = (empty($action_path)||!$action_path) ? (($URI == '/' || empty($URI)) ? 'main' : substr($URI,1)) : $action_path;

        operation_log(['type'=>'', 'userid'=> $data->data->id ,'username'=> $data->data->username ,'controller'=>$aKey,'action'=>$aKey,'uri'=>json_encode($this->U())]);

        if( !$data['code'] ) $code = 4001;

        return $code;
    }

    // 返回token和refresh_toke
    protected function Authorizations($data = [],$is_fresh = false){
        try {
            $time = time();
            $token = ['iat' => $time,'data' => $data];
            $access_token = $token;
            $access_token['scopes'] = 'access_token';
            $access_token['exp'] = $time + 86400 * 7;

            $refresh_token = $token;
            $refresh_token['scopes'] = 'refresh_toke';
            $refresh_token['exp'] = $time+( 86400 * 15 );
            $jsonList['access_token']  = JWT::encode($access_token,$this->secretKey);
            if( $is_fresh ) $jsonList['refresh_token'] = JWT::encode($refresh_token,$this->secretKey);
        }
        catch (\Exception $ex ){
            $jsonList = ['access_token' => $ex->getMessage()];
        }
        return ($jsonList);
    }

    protected function get_refresh_token($data = []){
        try {
            $time = time();
            $token = [
                'iat' => $time,
                'data' => $data
            ];
            $access_token = $token;
            $access_token['scopes'] = 'access_token';
            $access_token['exp'] = $time + 86400 * 7;

            $jsonList = [
                'access_token'=>JWT::encode($access_token,$this->secretKey),
            ];
        }catch (\Exception $ex ){
            $jsonList = [
                'msg'=>$ex->getMessage(),
            ];
        }

        return ($jsonList);
    }

    // 检测AccessToken是否合法
    protected function ckAuthoriztion(){
	    $msg = '验签失败';
        try {
            if($this->request->hasHeader('Authorization')) {
                $token = $this->request->getHeader('Authorization');
                if (!$token) return ["code" => false, "msg" => '验证失败'];
                $token = $token->getValue();
                $decoded = JWT::decode($token, $this->secretKey, ['HS256']);
                if ($decoded->scopes == 'access_token') return ["code" => true, "data" => $decoded];
            }
        }
        catch (\Exception $ex){
            return ["code"=>false,"msg"=> $ex->getMessage()];
        }
        return ["code"=>false,"status" => 0,"msg"=> $msg];
    }

    protected function userId () {
        $data = $this->ckAuthoriztion();
        return $data['code'] ? $data['data']->data->id : 0;
    }


    // 分頁码
    protected function _page(){
        $page = $this->request('currentPage');
        //$size = $this->request('size');
        return $page?:1;
    }
    // 分页大小
    protected function _size(){
        $size = $this->request('pageSize');
        return $size?:10;
    }
    // 排序字段
    protected function _s_name(){
        $filed = $this->request('sort');
        return $filed;
    }
    // 排序方向
    protected function _s_dir(){
        $s_dir = $this->request('dir');
        return $s_dir;
    }

    // 邮件发送
    protected function sent_mail($options = []){
        $resp = false;
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();                                            // Send using SMTP
            $mail->Host       = 'smtp.mxhichina.com';                   // Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
            $mail->Username   = 'admin@yimaotong.net';                  // SMTP username
            $mail->Password   = 'D!54g95XV5Mf63%';                      // SMTP password
            $mail->SMTPSecure = 'ssl';                                  // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
            $mail->Port       = 465;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
            $mail->CharSet='UTF-8';
            //Recipients
            $mail->setFrom('admin@yimaotong.net', '一贸通');
            $mail->addAddress( $options["to"]);     // Add a recipient
            // Content
            $mail->isHTML(true);                                  // Set email format to HTML
            $mail->Subject = $options["subject"];
            $mail->Body    = $options["body"];
            $resp = $mail->send();
        }
        catch ( Exception $ex ){
            log_message('error',"sent_mail:$mail->ErrorInfo");
        }
        return $resp;
    }

    protected $filed = [
        10001 => '验签失败,请检查参数是否正确!',
        4001=>'AccessToken Exp',
        10004=>'refreshToken Error!',
        10003=>'参数错误!',
        11001=>'访问失败,未授权'
    ];
}
